class Compiler {
  constructor(vm) {
    this.el = vm.$el
    this.vm = vm
    this.compile(this.el)
  }

  //编译模版，处理文本节点和元素节点
  compile(el) {
    const childNodes = el.childNodes
    Array.from(childNodes).forEach((node) => {
      if (this.isTextNode(node)) {
        //处理文本节点
        this.compileText(node)
      } else if (this.isElementNode(node)) {
        //处理元素节点
        this.compileElement(node)
      }
      //判断 node 是否有子节点,有子节点则递归调用处理
      if (node.childNodes && node.childNodes.length) {
        this.compile(node)
      }
    })
  }

  //编译元素节点,处理指令
  compileElement(node) {
    //遍历所有属性节点
    Array.from(node.attributes).forEach((attr) => {
      //判断是否为指令
      let attrName = attr.name
      if (attrName.startsWith('@')) attrName = `v-on:${attrName.substring(1)}`
      if (this.isDirective(attrName)) {
        //v-text --> text
        attrName = attrName.substring(2)
        const key = attr.value
        this.update(node, key, attrName)
      }
    })
  }

  //统一处理
  update(node, key, attrName) {
    let fnName = attrName
    let value = this.vm[key]
    //处理 on 事件
    if (fnName.startsWith('on:')) {
      fnName = 'on'
      value = attrName.substring(3)
    }
    console.log(node, key, attrName)
    const updateFn = this[`${fnName}Updater`]
    updateFn && updateFn.call(this, node, value, key)
  }

  //处理 v-text 指令
  textUpdater(node, value, key) {
    node.textContent = value
    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue
    })
  }

  //处理 v-model 指令
  modelUpdater(node, value, key) {
    node.value = value
    new Watcher(this.vm, key, (newValue) => {
      node.value = newValue
    })
    //注册事件，实现双向绑定
    node.addEventListener('input', () => {
      this.vm[key] = node.value
    })
  }

  //处理 v-html 指令
  htmlUpdater(node, value, key) {
    node.innerHTML = value
    new Watcher(this.vm, key, (newValue) => {
      node.innerHTML = newValue
    })
  }

  //处理 v-on 指令
  onUpdater(node, value, key) {
    node.addEventListener(value, () => {
      try {
        this.vm.$options.methods[key]()
      } catch {
        throw Error(`${key} 未定义`)
      }
    })
  }

  //编译文本节点，处理插值表达式
  compileText(node) {
    const reg = /\{\{(.+?)\}\}/
    const value = node.textContent
    if (reg.test(value)) {
      const key = RegExp.$1.trim()
      node.textContent = value.replace(reg, this.vm[key])
      //创建 Watcher 对象，当数据改变更新视图
      new Watcher(this.vm, key, (newValue) => {
        node.textContent = value.replace(reg, newValue)
      })
    }
  }

  //判断元素属性是否为指令
  isDirective(attrName) {
    return attrName.startsWith('v-')
  }

  //判断节点是否为文本节点
  isTextNode(node) {
    //nodeType===3为文本节点
    return node.nodeType === 3
  }

  //判断节点是否是元素节点
  isElementNode(node) {
    //noteType===1为元素节点
    return node.nodeType === 1
  }
}
